import threading
from django.utils.deprecation import MiddlewareMixin

# 线程本地存储
_thread_locals = threading.local()


def get_current_request():
    """获取当前请求对象"""
    return getattr(_thread_locals, 'request', None)


def get_current_user():
    """获取当前用户"""
    request = get_current_request()
    if request:
        return getattr(request, 'user', None)


def get_current_ip():
    """获取当前IP地址"""
    request = get_current_request()
    if request:
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip
    return ''


class RequestContextMiddleware(MiddlewareMixin):
    """请求上下文中间件，用于在信号处理中获取用户和IP信息"""

    def process_request(self, request):
        _thread_locals.request = request

    def process_response(self, request, response):
        # 清理线程本地存储
        if hasattr(_thread_locals, 'request'):
            del _thread_locals.request
        return response